from rest_framework import serializers
from django.core.validators import MinValueValidator, MaxValueValidator

from apps.address.models import Address

class AddressSerializer(serializers.ModelSerializer):
    """适配MySQL的序列化器"""
    class Meta:
        model = Address
        fields = '__all__'
        extra_kwargs = {
            'latitude': {
                'validators': [MinValueValidator(-90), MaxValueValidator(90)],
                'required': False
            },
            'longitude': {
                'validators': [MinValueValidator(-180), MaxValueValidator(180)],
                'required': False
            }
        }

    def validate(self, attrs):
        """同城校验"""
        if attrs.get('latitude') and not attrs.get('longitude'):
            raise serializers.ValidationError("必须同时提供经度和纬度")
        return attrs